package cn.itsource.mq.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @description: 消息生产者
 */
public class ProducerTest {

    //队列名称
    public static final String EXCHANGE_DIRECT = "exchange_topic2";

    /**
     * 步骤：
     * 1、创建连接
     * 2、创建信道
     * 3、创建交换机
     * 4、发送消息
     */
    public static void main(String[] args) throws Exception {
        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务地址
        factory.setHost("localhost");
        //1、创建连接，通过工厂获取连接
        //写在try里面，含义是：到时候会自动关闭连接
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //3、创建交换机
        channel.exchangeDeclare(EXCHANGE_DIRECT, BuiltinExchangeType.TOPIC);

        //4、发送消息
        for (int i = 1; i <= 5; i++) {
            //这里的第二个参数就是指定routingKey  指定路由过滤的key
            channel.basicPublish(EXCHANGE_DIRECT, "error.error", null, ("error" + i).getBytes());
            channel.basicPublish(EXCHANGE_DIRECT, "info.info.info.info.info", null, ("info" + i).getBytes());
            channel.basicPublish(EXCHANGE_DIRECT, "debug.debug.debug", null, ("debug" + i).getBytes());
        }
        System.out.println("消息发送完毕");
    }
}